﻿using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using Newtonsoft.Json;
using NetWorkTest;
namespace UDPComm{

    public class UDPClient
    {
        private static IPAddress GroupAddress = IPAddress.Parse("192.168.1.255");
        private UdpClient udp_client = new UdpClient();
        private static int GroupPort = 8089;
        IPEndPoint coming_endpoint = new IPEndPoint(0, 0);
        IPEndPoint groupEP = new IPEndPoint(GroupAddress, GroupPort);
        bool thread_flag = false;
        public UDPClient()
        {


        }
        public void Send(String message)
        {
 

            try
            {
                Console.WriteLine("Sending datagram : {0}", message);

                byte[] bytes = Encoding.ASCII.GetBytes(message);

                udp_client.Send(bytes, bytes.Length, groupEP);
               /* if (thread_flag == false)
                {
                    var th1 = new Thread(UdpReceiver);
                    th1.Start();
                    thread_flag = true;
                }*/

                //udp_client.Close();

            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }

        }
        public string UdpReceiver()
        {
        //    while (true)
          //  {
                byte[] rcvBytes = udp_client.Receive(ref coming_endpoint);

                string rcvMessage = Encoding.ASCII.GetString(rcvBytes, 0, rcvBytes.Length);
                Console.WriteLine("rcvMessage%s", rcvMessage);
                //private delegate void InvokeDelegate();
                return rcvMessage;
                //this.Invoke(new InvokeDelegate(NetWorkTest.Form1.InvokeUpdateIP));

           // }

        }


    }
}